package com.lilei.serialize;


import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * @Desc
 * @Auther 李雷(KyLin)
 * @Date 2020/03/31
 */
public class JavaXMLSerializer implements ISerializer {


    // 使用java的，必须要进行 get set 方法。同时需要再类中注解  @XmlRootElement
    @Override
    public <T> byte[] serialize(T obj) {



        // 创建输出流
        StringWriter sw = new StringWriter();
        try {
            // 利用jdk中自带的转换类实现
            JAXBContext context = JAXBContext.newInstance(obj.getClass());

            Marshaller marshaller = context.createMarshaller();
            // 格式化xml输出的格式
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
                    Boolean.TRUE);
            // 将对象转换成输出流形式的xml
            marshaller.marshal(obj, sw);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sw.toString().getBytes();
    }


    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {


        Object xmlObject = null;
        try {
            JAXBContext context = JAXBContext.newInstance(clazz);
            // 进行将Xml转成对象的核心接口
            Unmarshaller unmarshaller = context.createUnmarshaller();
            StringReader sr = new StringReader(new String(data));
            xmlObject = unmarshaller.unmarshal(sr);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return (T) xmlObject;

    }
}
